package com.xl6667.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.xl6667.domain.ResponseResult;
import com.xl6667.enums.AppHttpCodeEnum;
import com.xl6667.exception.SystemException;
import com.xl6667.service.UploadService;
import com.xl6667.util.PathUtils;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

@Service
@Data
@ConfigurationProperties(prefix = "aliyun")
public class uploadServiceImpl implements UploadService {

    @Override
    public ResponseResult uploadFile(MultipartFile img) {
        String filename = img.getOriginalFilename();
        //判断文件类型
        //获取原始文件名
        String originalFilename = img.getOriginalFilename();
        //对原始文件名进行判断
        if (!originalFilename.endsWith(".png") && !originalFilename.endsWith(".jpg")) {
            throw new SystemException(AppHttpCodeEnum.FILE_TYPE_ERROR);
        }
        //如果判断通过上传文件到OSS
        //设置文件上传地址
        String filePath = PathUtils.generateFilePath(originalFilename);
        uploadOss(img,filePath);
        //  2099/2/3/wqeqeqe.png
        return ResponseResult.okResult("https://"+bucketName+'.'+endpoint+'/'+filePath);
    }

    String endpoint;
    String accessKey;
    String accesskeySecret;
    String bucketName;
    /**
     * 文件上传
     * @param img
     * @param filePath
     * @return
     */
    private void uploadOss(MultipartFile img, String filePath) {
        OSS oss = new OSSClientBuilder().build(endpoint, accessKey, accesskeySecret);
        try {
            InputStream inputStream = img.getInputStream();
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName,filePath,inputStream);
            // 如果需要上传时设置存储类型和访问权限，请参考以下示例代码。
            // ObjectMetadata metadata = new ObjectMetadata();
            // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
            // metadata.setObjectAcl(CannedAccessControlList.Private);
            // putObjectRequest.setMetadata(metadata);
            // 上传字符串。
            PutObjectResult result = oss.putObject(putObjectRequest);

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }


}
